package com.winsdom.aspect;

import com.winsdom.annotation.OperationLog;
import com.winsdom.context.BaseContext;
import com.winsdom.entity.SysOperationLog;
import com.winsdom.service.ISysOperationLogService;
import com.winsdom.utils.IpAddressUtil;
import com.winsdom.utils.OperationLogUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private ISysOperationLogService sysOperationLogService;
    
    @After("@annotation(operationLog)")
    public void doBefore(JoinPoint joinPoint, OperationLog operationLog) {
        SysOperationLog log = new SysOperationLog();
        log.setOperationTime(LocalDateTime.now());
        log.setUserId(getCurrentUserId());
        String testIp=IpAddressUtil.getCurrentIpAddress();
        byte[] bytes = IpAddressUtil.ipToBytes(testIp);
        log.setIpAddress(bytes);
        log.setOperationFunction(joinPoint.getSignature().getName());
        log.setOperationDescription(operationLog.description());
        log.setIsDeleted(0);

        // 保存到数据库
        sysOperationLogService.save(log);
        
        // 同时记录到日志文件
        OperationLogUtil.log(
            log.getUserId(),
            testIp,
            log.getOperationFunction(),
            log.getOperationDescription()
        );
    }

    private Integer getCurrentUserId() {
        // 获取当前用户ID
        return BaseContext.getCurrentId();
    }
}
